package org.geppeto.eva.synchronizer;

import java.nio.channels.Channel;
import java.util.Map;
import java.util.HashMap;

import org.cometd.Bayeux;
import org.cometd.Client;
import org.cometd.Message;
import org.cometd.server.BayeuxService;

public class SyncService extends BayeuxService
{
	InstanceManager _mngInstance = null;
    public SyncService(Bayeux bayeux)
    {
        super(bayeux, "hello");
        subscribe("/service/hello", "processHello");        
        _mngInstance = InstanceManager.getInstanceManager();
        _mngInstance.setPubSub(this);
    }

    public void processHello(Client remote, Message message)
    {
        Map<String, Object> input = (Map<String, Object>)message.getData();
        String name = (String)input.get("name");

        Map<String, Object> output = new HashMap<String, Object>();
        output.put("greeting", "Hello, " + name);
        remote.deliver(getClient(), "/hello", output, null);
    }
        
    public void Notify(String channelName, String note){
    	Map<String, Object> data = new HashMap<String, Object>();
        data.put("msg", note);
    	org.cometd.Channel channel = getBayeux().getChannel(channelName, false);
    	channel.publish(null, data, null);
    }
    
    String RegisterChannel(String channelName){
    	try {
    		getBayeux().getChannel(channelName, true);
    	return "OK";
    	} catch (Exception ex) {
    		return "Failed";
    	}
    }
    
    public InstanceManager getInstanceManager() {
    	return _mngInstance;
    }
}
